/**
 * Weibo.com Inc.
 * Copyright (c) 2004-2012 All Rights Reserved.
 */
package com.hunlian.makelove.common;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * 
 * 
 * @author sina
 * @version $Id: DigestWrapperImpl.java, v 0.1 2012-8-16 下午1:47:49 sina Exp $
 */
public class DigestWrapperImpl implements DigestWrapper {

    //private static final Logger logger = Logger.getLogger(DigestWrapperImpl.class);
	/**
     * The method generate MD5 string based on BouncyCastle package, if the
     * input is null, it will return null.
     * 
     * The returned string is a 32 digits hex number, same as the md5() method in php.
	 * 
	 * @see com.creditease.common.util.digest.DigestWrapper#generateMd5(String)
	 */
	@Override
	public String generateMd5(final String input) {
		String output = null;

		// if input is null, return null
		try
		{
    		if (input != null) {
    		    final byte[] inputBytes = input.getBytes();
    		    MessageDigest md = MessageDigest.getInstance("MD5");
    		    md.update(inputBytes, 0, inputBytes.length);
    
    			final byte[] outputBytes = md.digest();
    
    			StringBuffer outputBuffer = new StringBuffer(40);
    			for (byte b : outputBytes) {
    			    String strHex = Integer.toHexString(b & 255);
    			    if(strHex.length()==1)
    			    {
    			        outputBuffer.append("0");
    			    }
    			    outputBuffer.append(strHex);
    			    
    			}
    			
    			output = outputBuffer.toString();
    		}
		}
		catch(NoSuchAlgorithmException e)
		{
		    //logger.error("获取md5算法失败", e);
			e.printStackTrace();
		}
		
		return output;
	}

}
